package cc.eddic.examinationsystem.config;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@Slf4j
@Component
public class LoggingAccessDeniedHandler implements AccessDeniedHandler {


    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException ex) throws IOException, ServletException {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        val name = null != auth ? auth.getName() : "unknown";
        val authority = null != auth ? auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(", ")) : "unknown";

        String url = request.getRequestURI();
        log.warn("{} [{}] was trying to access protected resource:  {}", name, authority, url);

        try {
            url = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            log.warn("encode url error", e);
        }
        response.sendRedirect(request.getContextPath() + "/403?url=" + url);

    }
}